import { BrowserWindow, BrowserWindowConstructorOptions, shell } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../../resources/icon.png?asset'

/**
 * 主窗口相关操作
 */
export default class MainFrame {
  public frame!: BrowserWindow
  private options: BrowserWindowConstructorOptions = {
    width: 950,
    height: 650,
    show: false,
    frame: false, // 无边框 无标题
    // titileBarStyle: 'hidden', // 隐藏标题栏
    // titleBarOverlay:{
    //    color: '#ffffff',
    //   symbolColor: '#74b1be'
    // },
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  }

  create(): void {
    this.frame = new BrowserWindow(this.options)

    // 默认打开devTools
    this.frame.webContents.openDevTools()

    this.frame.on('ready-to-show', () => {
      this.frame.show()
    })

    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'))
    }
  }

  close(): void {
    this.frame.close()
  }

  move(data: { appX: number; appY: number }) {
    this.frame.setPosition(data.appX, data.appY)
  }
}
